347. Top K Frequent Elements

题目 347. Top K Frequent Elements

image-b888e61b

思路分析

哈希计数+优先队列获取前top即可

java中HashMap常用api

java中priority_queue常用api

代码实现

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int num:nums){
            map.put(num,map.getOrDefault(num,0)+1);
        }

        PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a,b) -> map.get(b) - map.get(a));
        for(Integer num : map.keySet()){
            maxHeap.add(num);
        }

        int[] res=new int[k];
        int i=0;
        while(k--!=0){
            res[i++]=maxHeap.poll();
        }
        return res;
    }
}

同类题型

视频讲解